package com.ruoyi.web.controller.system;

import com.alibaba.fastjson.JSON;
import com.ruoyi.common.annotation.Anonymous;
import com.ruoyi.common.constant.Constants;
import com.ruoyi.common.core.domain.AjaxResult;
import com.ruoyi.common.core.domain.entity.SysMenu;
import com.ruoyi.common.core.domain.entity.SysUser;
import com.ruoyi.common.core.domain.model.LoginBody;
import com.ruoyi.common.core.redis.RedisCache;
import com.ruoyi.common.utils.SecurityUtils;
import com.ruoyi.framework.web.service.SysLoginService;
import com.ruoyi.framework.web.service.SysPermissionService;
import com.ruoyi.system.domain.RequestEntity;
import com.ruoyi.system.domain.vo.sendTask.SendTaskResponse;
import com.ruoyi.system.service.IProxyService;
import com.ruoyi.system.service.ISysMenuService;
import org.apache.commons.lang3.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RestController;

import java.io.IOException;
import java.util.ArrayList;
import java.util.List;
import java.util.Set;

/**
 * 登录验证
 *
 * @author ruoyi
 */
@RestController
public class SysLoginController {
    @Autowired
    private SysLoginService loginService;

    @Autowired
    private ISysMenuService menuService;

    @Autowired
    private SysPermissionService permissionService;

    @Autowired
    private IProxyService iProxyService;

    @Autowired
    private RedisCache redisCache;

    public static final String SUCCESS_CACHE_LIST = "SUCCESS_CACHE_LIST";

    public static final String SUCCESS_CACHE_LIST_NOTIFIED = "SUCCESS_CACHE_LIST_NOTIFIED";
    private static final Logger logger = LoggerFactory.getLogger(SysLoginController.class);

    /**
     * 登录方法
     *
     * @param loginBody 登录信息
     * @return 结果
     */
    @PostMapping("/login")
    public AjaxResult login(@RequestBody LoginBody loginBody) {
        AjaxResult ajax = AjaxResult.success();
        // 生成令牌
        String token = loginService.login(loginBody.getUsername(), loginBody.getPassword(), loginBody.getCode(),
                loginBody.getUuid());
        ajax.put(Constants.TOKEN, token);
        return ajax;
    }

    /**
     * 获取用户信息
     *
     * @return 用户信息
     */
    @GetMapping("getInfo")
    public AjaxResult getInfo() {
        SysUser user = SecurityUtils.getLoginUser().getUser();
        // 角色集合
        Set<String> roles = permissionService.getRolePermission(user);
        // 权限集合
        Set<String> permissions = permissionService.getMenuPermission(user);
        AjaxResult ajax = AjaxResult.success();
        ajax.put("user", user);
        ajax.put("roles", roles);
        ajax.put("permissions", permissions);
        return ajax;
    }

    /**
     * 获取路由信息
     *
     * @return 路由信息
     */
    @GetMapping("getRouters")
    public AjaxResult getRouters() {
        Long userId = SecurityUtils.getUserId();
        List<SysMenu> menus = menuService.selectMenuTreeByUserId(userId);
        return AjaxResult.success(menuService.buildMenus(menus));
    }


    /**
     * @param clickid
     * @return
     */

    @Anonymous
    @PostMapping("/testproxy")
    public AjaxResult testproxy(String clickid) {
        AjaxResult ajax = AjaxResult.success();
        logger.info("/aj/ios/testproxy回调的请求参数为:{}" ,clickid);
        List<String> arraylist = new ArrayList<>();
        arraylist.add(clickid);
        redisCache.setCacheList(SUCCESS_CACHE_LIST_NOTIFIED, arraylist);
        ajax.put("clickid", clickid);
        return ajax;
    }


    @Anonymous
    @PostMapping("/proxyToSDK")
    //这任务每半小时一次，一次刷10个请求
    public AjaxResult proxyToSDK(String count,String bundle_id) throws IOException {
        AjaxResult ajax = AjaxResult.success();
        if(StringUtils.isEmpty(count)){
            ajax.put("result", "count不能为空");
            return ajax;
        }
        if(StringUtils.isEmpty(bundle_id)){
            ajax.put("result", "bundle_id不能为空");
            return ajax;
        }
        RequestEntity entity = new RequestEntity();
        iProxyService.proxyToSDK(entity,count,bundle_id);
        return ajax;
    }

    @Anonymous
    @GetMapping("/aj/ios/getTask")
    public AjaxResult getTask(String bundle_id) {
        return iProxyService.getAjaxResult(bundle_id);
    }

    @Anonymous
    @PostMapping("/aj/ios/sendTask")
    public AjaxResult sendTask(@RequestBody List<SendTaskResponse> sendTaskResponse) {
        logger.info("/aj/ios/sendTask的请求参数为:{}" ,JSON.toJSONString(sendTaskResponse));
        AjaxResult ajax = AjaxResult.success();
        //最终发送任务过去的地址。
        sendTaskResponse.forEach(obj -> {
            iProxyService.sendRequestWithProxyReal(obj);
        });
        return ajax;
    }


}
